<script>
export default {
  name: 'SelectAddress',
  emits: ['selectAddressSuccess'],
  data() {
    return {
      /* 省的数据列表 */
      province: [],
      /* 省的ID */
      provinceId: '',
      /* 市的数据列表 */
      city: [],
      /* 市的ID */
      cityId: '',
      /* 区县的数据 */
      county: [],
      /* 区县的ID */
      countyId: ''
    }
  },
  methods: {
    /*
    *获取地址信息的回调函数
    *  */
    async fetchAddressList(parentId) {
      try {
        return await this.$store.dispatch('organizationStore/fetchAddressListAction', parentId)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 获取市 */
    fetchCityList() {
      this.fetchAddressList(this.provinceId).then(city => {
        this.city = city
      })
    },
    /* 获取区县 */
    async fetchCountyList() {
      this.fetchAddressList(this.cityId).then(county => {
        this.county = county
      })
    },
    /*
    *
    * 向父组件触发自定义事件
    *  */
    selectSuccess() {
      this.$emit('selectAddressSuccess', { provinceId: this.provinceId, cityId: this.cityId, countyId: this.countyId })
    }
  },
  mounted() {
    /* 获取省 */
    this.fetchAddressList().then(province => {
      this.province = province
    })
  }
}
</script>

<template>
  <div class="select-address">
    <el-select placeholder="省" v-model="provinceId" @change="fetchCityList">
      <el-option v-for="item in province" :value="item.id" :label="item.name" :key="item.id"></el-option>
    </el-select>

    <el-select placeholder="市" v-model="cityId" @change="fetchCountyList">
      <el-option v-for="item in city" :value="item.id" :label="item.name" :key="item.id"></el-option>
    </el-select>

    <el-select placeholder="县" v-model="countyId" @change="selectSuccess">
      <el-option v-for="item in county" :value="item.id" :label="item.name" :key="item.id"></el-option>
    </el-select>
  </div>
</template>

<style scoped lang="scss">
.el-select {
  width: 80px;
  margin: 0 2px;
}
</style>
